package com.kischang.blog.utils;

import javax.activation.DataHandler;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

public class Utils {
	static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	public static String formatDate(){
		return format.format(Calendar.getInstance().getTime());
	}
	public static String formatDate(Date date){
		return format.format(date);
	}
	public static String createUUID(){
		return UUID.randomUUID().toString();
	}
	public static boolean isNull(String str){
		return str==null || "".equals(str);
	}
	public static String getActivecode(int faildhour){
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.HOUR,faildhour);
		return createUUID()+"|"+formatDate(calendar.getTime());
	}
	public static boolean sendMail(String sendTo, String subject,String textContent) {
		String rv = sendEmail("smtp.qq.com"
				, "TRUE", "2731128291@qq.com"
				, "7845120c"
				, sendTo, subject, textContent);
		if(rv == null){
			return true;
		}
		System.err.println(rv);
		return false;
	}
	
	public static String sendEmail(String smtpHost, String smtpAuth, String sendBy, String password, String sendTo, String title, String content) {
        Properties prop = new Properties();
        prop.put("mail.smtp.host", smtpHost);
        prop.put("mail.smtp.auth", smtpAuth);
        prop.put("mail.transport.protocol", "smtp");
        System.out.println(sendTo);
        System.out.println(title);
        System.out.println(content);

        //创建邮件会话
        Session session = Session.getInstance(prop);
        session.setDebug(false);

        //构造信息体
        MimeMessage message = new MimeMessage(session);
        // 发件地址
        try {
            Address byAddress = new InternetAddress(sendBy);
            message.setFrom(byAddress);
            //收件地址
            Address toAddress = new InternetAddress(sendTo);
            message.setRecipient(MimeMessage.RecipientType.TO, toAddress);
            //主题
            message.setSubject(title);
            //正文
            StringBuilder sb = new StringBuilder();
            sb.append("<HTML><BODY>");
            sb.append(content.replaceAll("\r\n","<br/>").replaceAll(" ", "&nbsp;"));
            sb.append("</BODY></HTML>");
            message.setDataHandler(new DataHandler(new ByteArrayDataSource(sb.toString(), "text/html")));
            message.saveChanges();
            Transport transport = session.getTransport("smtp");
            transport.connect(smtpHost, sendBy, password);
            //发送
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        } catch (AddressException e) {
            e.printStackTrace();
            return e.getMessage();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
            return "没有找到对应的邮件提供商！！！";
        } catch (MessagingException e) {
            e.printStackTrace();
            if(e instanceof AuthenticationFailedException){
                return "发送方用户名密码错误！！！";
            }
            return e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            return e.getMessage();
        }
        return null;
    }

    public static String randomStr(int length){
        String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
        StringBuilder code = new StringBuilder();
        for(int i=0;i<length;i++){
            String c = base.charAt(new Random().nextInt(base.length())) + "";
            code.append(c);
        }
        return code.toString();
    }
}
